package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class MyServer {

    // 定义一个 数据包插口
   private   DatagramSocket socker  = null;


   // 构造方法
    public MyServer(int port) throws SocketException {
        // 进行进程和 端口号的连接
        socker = new DatagramSocket(port);

    }


    public void start()  throws IOException {

            while(true) {
                System.out.println("服务器开始运行...");

//        打包数据包基本单位
                DatagramPacket requestPacket = new DatagramPacket(new byte[4096],
                        4096 );

//        接受客户端发来的数据
                socker.receive(requestPacket);

                // 转为成字符串打印日志
                String request = new String(requestPacket.getData(),
                        0, requestPacket.getLength());


                // 执行业务逻辑并对客户端进行响应
                String response = process(request);


//              打包一组响应的数据包
//            注意这里要带上对应客户端输入的ip地址和端口号
                DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,
                        response.getBytes().length,
                        requestPacket.getSocketAddress());

                // 进行响应回服务器中
                socker.send(responsePacket);

                // 打印日志
                System.out.printf("[ip地址为：%s, %s,端口号为：%d, %d 客户端的的需求的为: %s, 服务器的响应为: %s]\n",
                        requestPacket.getAddress(),responsePacket.getAddress(),
                        responsePacket.getPort(),requestPacket.getPort(),
                        request, response);
            }
    }



    // 业务逻辑的方法
    public String process(String request) {
        return request;
    }



    public static void main(String[] args) throws IOException{
        MyServer  myServer = new MyServer(9090);
        myServer.start();
    }
}
